#include "StdAfx.h"
#include "UpdateManager.h"
#include "http/Connection.h"
#include "xml/xml_op.h"
#include <time.h>

#define DAY	(1 * 60 * 60 * 24)

struct CurrentVersion
{
	CString version;
	CString update_link;
};

XML_SERIALIZE_MAP(CurrentVersion)
	XML_MAP_ELEMENT(version)
	XML_MAP_ELEMENT(update_link)
XML_END_SERIALIZE_MAP()

CUpdateManager::CUpdateManager(void)
{
}

bool CUpdateManager::IsUpToDate(BOOL bForceCheck/* = FALSE*/)
{
	Configuration cfg;

	LONGLONG last_checked = cfg.lastCheckForUpdateTime;

	__time64_t current_time = 0;
	_time64(&current_time);

	if (!bForceCheck && current_time < last_checked + cfg.checkForUpdateInterval * DAY) 
		return true;

	CWaitCursor wait;

	cfg.lastCheckForUpdateTime = (ULONGLONG)current_time;

	HTTP::Connection httpConnection;
	if (!httpConnection.Open( GetString(IDS_CURRENT_VERSION_URL) ))
		return true;

	CStringA strResponse;
	if (!httpConnection.GetResponse(strResponse))
        return true;

	CurrentVersion last_version;
	if (!(((CString)strResponse) >> last_version))
		return true;

	CString version = UTIL::GetVersion();

	// Get current update link
	if (!last_version.update_link.IsEmpty())
		m_strUpdateURL = last_version.update_link;

	ATLASSERT(!version.IsEmpty());
	ATLASSERT(!last_version.version.IsEmpty());

	if (last_version.version.IsEmpty() || version.IsEmpty())
		return true;

	return version == last_version.version;
}
